package com.jy.modules.cims.logger.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.JResult;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.common.sysUtils.SpringContextUtils;
import com.jy.modules.cims.component.common.service.TCMmTaskLogService;
import com.jy.modules.cims.creditright.service.SettleAndSecondBuyService;
import com.jy.modules.cims.data.common.dto.TCMmTaskLogDTO;
import com.jy.modules.cims.data.dto.CreditPackageDto;
import com.jy.modules.cims.settle.service.SettleService;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;
import com.jy.platform.restservice.web.base.BaseController;

/**
 * 自动匹配债权预留额度 ClassName: QuotaEstimateController
 * 
 * @Description: TODO
 * @author dell
 * @date 2015-11-5
 */
@Controller
@Scope("prototype")
@RequestMapping("/loggerhistory")
public class LoggerHistoryController extends BaseController {

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmTaskLogService")
	public TCMmTaskLogService taskLogService;

	@Autowired
	@Qualifier("com.jy.modules.cims.settle.service.SettleService")
	public SettleService settleService;

	@Autowired
	@Qualifier("com.jy.modules.cims.creditright.service.SettleAndSecondBuyService")
	public SettleAndSecondBuyService settleAndSecondBuyService;

	@Autowired
	private SpringContextUtils springContextUtils;

	@RequestMapping(value = "/prepareExecute/{operate}")
	public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
		ModelAndView model = new ModelAndView();
		if ("toQuery".equals(operate)) {// 跳转至 查询页面
			model.setViewName("cims/logger/queryLoggerHistory");
			return model;
		}else if ("toTotalQuery".equals(operate)) {// 跳转至 查询页面
			model.setViewName("cims/logger/queryLoggerHistoryTotal");
			return model;
		}
		return model;
	}

	@RequestMapping(value = "/queryLoggerHistoryList")
	@ResponseBody
	public DataMsg queryQuotaEstimateList(HttpServletRequest request, TCMmTaskLogDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {

		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);

		List<TCMmTaskLogDTO> list = taskLogService.searchTCMmTaskLogByPaging(params.getSearchParams());
		dataMsg.setData(list);

		dataMsg.setTotalRows(pageInfo.getTotalCount());
		return dataMsg;
	}
	/**
	 * 
	 * @Title queryQuotaEstimateTotalList
	 * @Description TODO
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return
	 * @throws Exception 
	 * DataMsg 
	 * @date 2016-11-14-上午9:41:19
	 * @update 
	 * @throws
	 */
	@RequestMapping(value = "/queryLoggerHistoryTotalList")
	@ResponseBody
	public DataMsg queryQuotaEstimateTotalList(HttpServletRequest request, TCMmTaskLogDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {

		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);

		List<TCMmTaskLogDTO> list = taskLogService.searchTCMmTaskLogTotalByPaging(params.getSearchParams());
		dataMsg.setData(list);

		dataMsg.setTotalRows(pageInfo.getTotalCount());
		return dataMsg;
	}

	/**
	 * 页面根据id单条自动月还和二次购买处理
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/batchSettleAndSecondBuy")
	@ResponseBody
	public DataMsg batchSettleAndSecondBuy(HttpServletRequest request, TCMmTaskLogDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
		// 根据Id获取对象要传参数：机构编码，合约编码，债权包名称，结算日期
		TCMmTaskLogService tcmmTaskLogService = springContextUtils.getBean(TCMmTaskLogService.class);
		TCMmTaskLogDTO queryTaskLogDto = new TCMmTaskLogDTO();
		queryTaskLogDto.setId(dto.getId());
		List<TCMmTaskLogDTO> tcmmTaskLogDTOList = tcmmTaskLogService.searchTCMmTaskLog(SearchParamUtil.getSearchParam(queryTaskLogDto));

		// 处理 批量结算和二次购买
		CreditPackageDto creditPackageDto = new CreditPackageDto();
		String settleDate = DateTimeUtils.formatDate(tcmmTaskLogDTOList.get(0).getSettleDate(), "yyyy-MM-dd");
		creditPackageDto.setSettleDate(settleDate);
		creditPackageDto.setCooperorgCode(tcmmTaskLogDTOList.get(0).getCooperorgCode());
		creditPackageDto.setContractCode(tcmmTaskLogDTOList.get(0).getContractCode());
		creditPackageDto.setCreditPackageName(tcmmTaskLogDTOList.get(0).getCreditPackageName());
		JResult resut = settleService.batchSettleAndSecondBuy(creditPackageDto, false);
		if (SimpleStringUtils.hasText(resut.getErrMsg())) {
			logger.info("二次购买处理失败：" + resut.getErrMsg());
			dataMsg.setStatus("error");
			dataMsg.setMsg(resut.getErrMsg());
			return dataMsg;
		}

		dataMsg = super.initDataMsg(dataMsg);
		dataMsg.setStatus("ok");
		dataMsg.setMsg("处理成功");
		return dataMsg;
	}

	@RequestMapping(value = "/delSettleAndSecondBuy")
	@ResponseBody
	public DataMsg delSettleAndSecondBuy(HttpServletRequest request, TCMmTaskLogDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
		try {
			// 根据Id获取对象要传参数：机构编码，合约编码，债权包名称，结算日期
			TCMmTaskLogService tcmmTaskLogService = springContextUtils.getBean(TCMmTaskLogService.class);
			TCMmTaskLogDTO queryTaskLogDto = new TCMmTaskLogDTO();
			queryTaskLogDto.setId(dto.getId());
			List<TCMmTaskLogDTO> tcmmTaskLogDTOList = tcmmTaskLogService.searchTCMmTaskLog(SearchParamUtil.getSearchParam(queryTaskLogDto));
			if (CollectionsUtils.isEmpty(tcmmTaskLogDTOList)) {
				dataMsg.setStatus("error");
				dataMsg.setMsg("数据不存在！");
				return dataMsg;
			}

			// 删除处理 批量结算和二次购买
			String settleDate = DateTimeUtils.formatDate(tcmmTaskLogDTOList.get(0).getSettleDate(), "yyyy-MM-dd");
			settleAndSecondBuyService.deleteSettleAndSecondBuy(tcmmTaskLogDTOList.get(0).getCooperorgCode(), tcmmTaskLogDTOList.get(0).getContractCode(),
					    tcmmTaskLogDTOList.get(0).getCreditPackageName(), settleDate, true);

			dataMsg = super.initDataMsg(dataMsg);
			dataMsg.setStatus("ok");
			dataMsg.setMsg("重置成功");
			
		} catch (Exception e) {
			dataMsg.setStatus("error");
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteSettleAndSecondBuy异常：", e);
		}
		return dataMsg;
	}

	/**
	 * @author 周鹏
	 * @description:新增单条自动月还和二次购买处理
	 * @date 2015-11-10 20:32:17
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/insertSettleAndSecondBuy")
	@ResponseBody
	public DataMsg insertSettleAndSecondBuy(HttpServletRequest request, TCMmTaskLogDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
		try {
			QueryReqBean params = new QueryReqBean();
			Map<String, Object> searchParams = new HashMap<String, Object>();
			searchParams.put("dto", dto);
			params.setSearchParams(searchParams);
			List<TCMmTaskLogDTO> list = taskLogService.searchTCMmTaskLog(params.getSearchParams());
			// 查询日志表，如果有数据提示数据已经存在
			if (list.size() > 0) {
				dataMsg.setStatus("error");
				dataMsg.setMsg("数据已经存在！不允许新增。");
				return dataMsg;
			}

			CreditPackageDto creditPackageDto = new CreditPackageDto();
			String settleDate = DateTimeUtils.formatDate(dto.getSettleDate(), "yyyy-MM-dd");
			creditPackageDto.setSettleDate(settleDate);
			creditPackageDto.setCooperorgCode(dto.getCooperorgCode());
			creditPackageDto.setContractCode(dto.getContractCode());
			creditPackageDto.setCreditPackageName(dto.getCreditPackageName());
			List<CreditPackageDto> CreditPackagelist = settleAndSecondBuyService.searchCreditPackageForSettle(creditPackageDto);
			// 查询结算包信息，如果不存在结算包信息，提示没符合要求的结算数据
			if (CreditPackagelist.size() == 0) {
				dataMsg.setStatus("error");
				dataMsg.setMsg("没符合要求的结算数据，请重新输入");
				return dataMsg;
			}
			settleService.batchSettleAndSecondBuy(creditPackageDto, false);
			dataMsg = super.initDataMsg(dataMsg);
			dataMsg.setStatus("ok");
			dataMsg.setMsg("新增成功");
		} catch (Exception e) {
			dataMsg.setStatus("error");
			dataMsg.failed(e.getMessage());
			logger.error("执行方法insertSettleAndSecondBuy异常：", e);
		}
		return dataMsg;
	}

}
